package com.handpay.nocardpay.baselibrary.account.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.google.zxing.common.StringUtils;
import com.handpay.nocardpay.baselibrary.account.model.bean.Account;
import com.handpay.nocardpay.baselibrary.account.model.bean.UserLoginValidateBean;
import com.handpay.nocardpay.baselibrary.account.model.impl.UserLogInModelImpl;
import com.handpay.nocardpay.baselibrary.account.view.ILoginView;
import com.handpay.nocardpay.baselibrary.account.view.IUserLoginValidateView;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.model.IBaseModel;
import com.handpay.nocardpay.baselibrary.commbase.model.bean.BaseErrorInfo;
import com.handpay.nocardpay.baselibrary.commbase.presenter.IBasePresenter;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.http.HttpHeadFactory;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.threadmanager.ThreadPoolFactory;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;

/**
 * Created by sxshi on 2017/8/10.
 */

public class AccountPresenterImpl implements IBasePresenter {
    private UserLogInModelImpl logInModel;
    private ILoginView mLoginView;
    private IUserLoginValidateView mUserLoginValidateView;
    private Context mContext;

    public void setUserLoginValidateView(IUserLoginValidateView mUserLoginValidateView) {
        this.mUserLoginValidateView = mUserLoginValidateView;
    }

    public void setmLoginView(ILoginView mLoginView) {
        this.mLoginView = mLoginView;
    }


    public AccountPresenterImpl(Context context) {
        this.logInModel = new UserLogInModelImpl(context);
        this.mContext = context;
    }

    /**
     * 无卡账户登录
     *
     * @param paramers
     * @param clzz
     * @param isShowLoading
     */
    public void noCardPayLogin(HashMap<String, Object> paramers, Class<Account> clzz, boolean isShowLoading) {
        if (mLoginView != null) {
            if (isShowLoading) mLoginView.showProgress();
        }
        logInModel.noCardPayLogin(paramers, clzz, new IBaseModel.OnRequestFinishedListener<Account>() {
            @Override
            public void onError(BaseErrorInfo baseErrorInfo) {
                if (mLoginView != null) {
                    mLoginView.hideProgress();
                    mLoginView.showErrorAlert(baseErrorInfo);
                }
            }

            @Override
            public void onSuccess(Account response) {
                if (mLoginView != null) {
                    mLoginView.hideProgress();
                    if (response.responseCode.equals("U018") || response.responseCode.equals("U008") || response.responseCode.equals("U033")) {
                        mLoginView.loginError(response.errMessage);
                        AccountUtils.removeRMSPWDData();
                        return;
                    }
                    if (TextUtils.isEmpty(HttpHeadFactory.sessionID)) {
                        mLoginView.noSessionId();
                        return;
                    }
                    NoCardPayConfig.isNoCardPay = NoCardPayConstant.NOCARDPAY;
                    if (!TextUtils.isEmpty(response.getGesturePwd())) {
                        String gesture_pwd = SecureManager.getInstance().des(response.getGesturePwd(), 0, null);
                        String phoneNo = SecureManager.getInstance().des(response.getPhone(), 0, null);
                        ClientEngine.getInstance().saveRMSData(BaseProtocolKey.KEY_GESTURE_PWD, gesture_pwd);
                        if (AccountUtils.getAccountPhone(mContext) == null) {//手势密码用户安装后第一次登录成功
//                            HPLog.i(HPLog.YL_TAG, "手势密码用户安装后第一次登录成功");
                            PreferenceManager.getInstance(mContext).putBoolean(BaseProtocolKey.KEY_GESTURE_PWD_SWITCH_STATUS, true);
                        } else if (!AccountUtils.getAccountPhone(mContext).equals(phoneNo)) {//切换成手势密码用户
//                            HPLog.i(HPLog.YL_TAG, "切换成手势密码用户 old:" + AccountUtils.getAccountPhone(mContext) + "new:" + phoneNo);
                            PreferenceManager.getInstance(mContext).putBoolean(BaseProtocolKey.KEY_GESTURE_PWD_SWITCH_STATUS, true);
                        } else {
//                            HPLog.i(HPLog.YL_TAG, "老用户登录");
                        }
                        //返回密码不为空,没有手势密码开关存储记录
//                        if (PreferenceManager.getInstance(mContext).contains(BaseProtocolKey.KEY_GESTURE_PWD_SWITCH_STATUS) == false) {
//                            PreferenceManager.getInstance(mContext).putBoolean(BaseProtocolKey.KEY_GESTURE_PWD_SWITCH_STATUS, true);
//                        }
//                        HPLog.i(HPLog.YL_TAG, "login gesutre pwd:" + gesture_pwd);
                    } else {
                        ClientEngine.getInstance().removedData(BaseProtocolKey.KEY_GESTURE_PWD);
                        ClientEngine.getInstance().removedData(BaseProtocolKey.KEY_GESTURE_PWD_SWITCH_STATUS);
                    }
                    saveAccountInfo(response);
                    //友盟统计用户登录方式
                    countUserEvent(response, mContext, "NocardUserLogin", "手付通用户登录");
                    mLoginView.navigateToHome();
                }
            }
        });
    }

    /**
     * 秒秒通用户登录
     *
     * @param paramers
     * @param clzz
     * @param isShowLoading
     */
    public void fastbillLogin(HashMap<String, Object> paramers, Class<Account> clzz, boolean isShowLoading) {
        if (mLoginView != null) {
            if (isShowLoading) mLoginView.showProgress();
        }
        logInModel.fastbillLogin(paramers, clzz, new IBaseModel.OnRequestFinishedListener<Account>() {
            @Override
            public void onError(BaseErrorInfo baseErrorInfo) {
                if (mLoginView != null) {
                    mLoginView.hideProgress();
                    mLoginView.showErrorAlert(baseErrorInfo);
                }
            }

            @Override
            public void onSuccess(Account response) {
                if (mLoginView != null) {
                    mLoginView.hideProgress();
                    if (response.responseCode.equals("U018") || response.responseCode.equals("U008") || response.responseCode.equals("U033")) {
                        mLoginView.loginError(response.errMessage);
                        AccountUtils.removeRMSPWDData();
                        return;
                    }
                    if (TextUtils.isEmpty(HttpHeadFactory.sessionID)) {
                        mLoginView.noSessionId();
                        return;
                    }
                    NoCardPayConfig.isNoCardPay = NoCardPayConstant.FASTBILL;
                    saveAccountInfo(response);
                    countUserEvent(response, mContext, "FastbillUserLogin", "秒秒通用户登录");

                    mLoginView.navigateToHome();
                }
            }
        });
    }


    /**
     * 秒秒通用户登录
     *
     * @param paramers
     * @param clzz
     * @param isShowLoading
     */
    public void gestureLogin(HashMap<String, Object> paramers, Class<Account> clzz, boolean isShowLoading) {
        if (mLoginView != null) {
            if (isShowLoading) mLoginView.showProgress();
        }
        logInModel.gestureLogin(paramers, clzz, new IBaseModel.OnRequestFinishedListener<Account>() {
            @Override
            public void onError(BaseErrorInfo baseErrorInfo) {
                if (mLoginView != null) {
                    mLoginView.hideProgress();
                    mLoginView.showErrorAlert(baseErrorInfo);
                }
            }

            @Override
            public void onSuccess(Account response) {
                if (mLoginView != null) {
                    mLoginView.hideProgress();
                    if (response.responseCode.equals("U018") || response.responseCode.equals("U008") || response.responseCode.equals("U033")) {
                        mLoginView.loginError(response.errMessage);
                        AccountUtils.removeRMSPWDData();
                        return;
                    }
                    if (TextUtils.isEmpty(HttpHeadFactory.sessionID)) {
                        mLoginView.noSessionId();
                        return;
                    }
                    NoCardPayConfig.isNoCardPay = NoCardPayConstant.NOCARDPAY;
                    if (!TextUtils.isEmpty(response.getGesturePwd())) {
                        String gesture_pwd = SecureManager.getInstance().des(response.getGesturePwd(), 0, null);
                        HPLog.i(HPLog.YL_TAG, "login gesutre pwd:" + gesture_pwd);
                        ClientEngine.getInstance().saveRMSData(BaseProtocolKey.KEY_GESTURE_PWD, gesture_pwd);
                    }
                    saveAccountInfo(response);
                    //友盟统计用户登录方式
                    countUserEvent(response, mContext, "NocardUserLogin", "手付通用户登录");
                    mLoginView.navigateToHome();
                }
            }
        });
    }

    /**
     * @param paramers
     * @param clzz
     * @param isShowLoading
     */
    public void getUserLoginValidate(HashMap<String, Object> paramers, Class<UserLoginValidateBean> clzz, boolean isShowLoading) {

        if (mUserLoginValidateView != null) {
            if (isShowLoading)
                mUserLoginValidateView.showProgress();
        }
        logInModel.getUserLoginValidate(paramers, clzz, new IBaseModel.OnRequestFinishedListener<UserLoginValidateBean>() {
            @Override
            public void onError(BaseErrorInfo baseErrorInfo) {
                if (mUserLoginValidateView != null) {
                    mUserLoginValidateView.hideProgress();
                    mUserLoginValidateView.showErrorAlert(baseErrorInfo);
                }
            }

            @Override
            public void onSuccess(UserLoginValidateBean response) {

                if (mUserLoginValidateView != null) {
                    mUserLoginValidateView.hideProgress();
                    if (Integer.valueOf(response.getStatus()) == 1) {
                        mUserLoginValidateView.validateSuccess();
                    } else {
                        mUserLoginValidateView.validateError(response.getMessage());
                    }

                }
            }
        });
    }

    /**
     * 统计登录渠道
     *
     * @param response          用户信息
     * @param mContext          context
     * @param fastbillUserLogin 时间名称
     */
    private void countUserEvent(final Account response, final Context mContext, final String fastbillUserLogin, final String description) {
        ThreadPoolFactory.getNormalPool().execute(new Runnable() {
            @Override
            public void run() {
                String account = SecureManager.getInstance().des(response.getAccount(), 0, null);
                account = SecureManager.getInstance().des(account, 1, NoCardPayConfig.KEY_SECURE);
                HashMap<String, String> umengMap = new HashMap<>();
                umengMap.put("userAccount", account);
                umengMap.put("Description", description);
                umengMap.put("tudid", ClientEngine.getInstance().getDeviceUuid());
                MobclickAgent.onEvent(mContext, fastbillUserLogin, umengMap);
            }
        });

    }


    /**
     * 保存用户数据
     *
     * @param response 用户信息
     */
    private void saveAccountInfo(final Account response) {
        ThreadPoolFactory.getNormalPool().execute(new Runnable() {
            @Override
            public void run() {
                String account = response.getAccount();
                String phone = response.getPhone();
                String status = response.getStatus();
                String shopName = response.getShopName();
                account = SecureManager.getInstance().des(account, 0, null);
                phone = SecureManager.getInstance().des(phone, 0, null);
                shopName = SecureManager.getInstance().des(shopName, 0, null);
                String failDescription = response.getFailDescription();
                String merchantCode = response.getMerchantCode();
                Object status_obj = response.getPasswdStatus();
                String userId = SecureManager.getInstance().des(response.getUserID(), 0, null);
                AccountUtils.saveAccount(mContext, account, phone, AccountUtils.convertStatus(status), failDescription, merchantCode, userId);
                AccountUtils.saveRMSAccountName(account);
                AccountUtils.setShopName(mContext, shopName);
                if (status_obj != null) {
                    String passwdStatus = (TextUtils.isEmpty(String.valueOf(status_obj)) || String.valueOf(status_obj).equals("null")) ? "0" : String.valueOf(status_obj);//密码是否过期，0不过期，1 15天内需更改密码  2 密码已过期只能只能修改密码
                    AccountUtils.savePasswordStatus(mContext, (TextUtils.isEmpty(passwdStatus) || passwdStatus.equals("null")) ? 0 : Integer.parseInt(passwdStatus));
                }
            }
        });

    }

    @Override
    public void onDestory() {
        if (mLoginView != null) {
            mLoginView = null;
        }
    }
}
